package weaver.ofs.interfaces;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.RecordSet;
import weaver.workflow.request.todo.DataObj;
import weaver.workflow.request.todo.RequestStatusObj;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.*;

/**
 * 本示例，只将接受的数据打印在log/ecology中，具体的接口调用操作，请在相关数据遍历中执行。
 * 实现weaver.ofs.interfaces.SendRequestStatusDataInterfaces接口中SendRequestStatusData
 */
public class TestSendImpl2 implements SendRequestStatusDataInterfaces {
    private static final Log log = LogFactory.getLog(TestSendImpl2.class);

    /**
     * 后台设置id
     */
    public String id;
    /**
     * 设置的系统编号
     */
    public String syscode;
    /**
     * 服务器URL
     */
    public String serverurl;
    /**
     * 流程白名单
     */
    public ArrayList<String> workflowwhitelist;
    /**
     * 人员白名单
     */
    public ArrayList<String> userwhitelist;


    public String getId() {
        return id;
    }

    public String getSyscode() {
        return syscode;
    }

    public String getServerurl() {
        return serverurl;
    }

    public ArrayList<String> getWorkflowwhitelist() {
        return workflowwhitelist;
    }

    public ArrayList<String> getUserwhitelist() {
        return userwhitelist;
    }

    public static void main(String[] args) {
        String usercodeByUid = getUsercodeByUid(1);
        System.out.println(usercodeByUid);
    }

    /**
     * 实现消息推送的具体方法
     *
     * @param datas 传入的请求数据对象数据集
     */
    public synchronized void SendRequestStatusData(ArrayList<DataObj> datas) {

        log.info("Ecology统一待办数据推送金盛兰云台：start");
        log.info("datas的尺寸大小："+datas.size());

        for (DataObj dobj : datas) {
            log.info("【流程ID:"+dobj.getRequestid()+"】的数据处理...");
            JSONObject todojson = new JSONObject();
            JSONObject donejson = new JSONObject();
            JSONObject deljson = new JSONObject();

            ArrayList<RequestStatusObj> tododatas = dobj.getTododatas();
            log.info("显示待办数据："+tododatas.size());
            // 待办人数组
            List<Map<String, Object>> assignArray = new ArrayList<>();
            if (tododatas.size() > 0) {//处理推送的待办数据
                for (RequestStatusObj rso : tododatas) {
                    //遍历当前发送的待办数据
                    log.info("【流程ID:"+rso.getRequestid()+"】待办数据处理...");
                    ObjectMapper objectMapper = new ObjectMapper();
                    String rsoString = null;
                    try {
                        rsoString = objectMapper.writeValueAsString(rso);
                    } catch (JsonProcessingException e) {
                        log.info(e.getMessage());
                    }
                    log.info(rsoString);
                    // 待办
                    Map<String, Object> todoMap = new HashMap<>();
                    todoMap.put("actvName",rso.getNodename());
                    todoMap.put("msgInfoType",2);
                    todoMap.put("username",rso.getUser().getUsername());
                    todoMap.put("taskId", rso.getCid() + "");
                    String usercode = getUsercodeByUid(rso.getUser().getUID());
                    todoMap.put("usercode", usercode);
                    todoMap.put("remark", ""); // 如果有备注，替换为空字符串
                    todoMap.put("note", "");   // 如果有注释信息，替换为空字符串
                    log.info("待办人员名称："+rso.getUser().getUsername()+"，待办人员编码："+usercode+"，taskId："+rso.getCid()+"，待办人员id："+rso.getUser().getUID());
                    assignArray.add(todoMap);
                }
                todojson.put("oprType", "submit");
                todojson.put("assignArray", assignArray);
            }

            ArrayList<RequestStatusObj> donedatas = dobj.getDonedatas();
            log.info("显示已办数据："+donedatas.size());
            if (donedatas.size() > 0) {//处理推送的已办数据
                for (RequestStatusObj rso : donedatas) {//遍历当前发送的已办数据
                    log.info("【流程ID:"+rso.getRequestid()+"】已办数据处理...");
                    ObjectMapper objectMapper = new ObjectMapper();
                    String rsoString = null;
                    try {
                        rsoString = objectMapper.writeValueAsString(rso);
                    } catch (JsonProcessingException e) {
                        log.info(e.getMessage());
                    }
                    log.info(rsoString);
                    //发送待办消息时，添加上一条已办人员的信息
                    todojson.put("passActvName", rso.getNodename()); // 待办记录已办环节名称
                    todojson.put("passTaskId", rso.getCid() + "");
                    todojson.put("passUserName", rso.getUser().getUsername());
                    todojson.put("passUid", rso.getUser().getUID());



                }
            }

            ArrayList<RequestStatusObj> deldatas = dobj.getDeldatas();
            log.info("显示删除数据："+deldatas.size());
            if (deldatas.size() > 0) {
                //处理推送的删除数据
                JSONArray todolist = new JSONArray();
                for (RequestStatusObj rso : deldatas) {//遍历当前发送的删除数据
                    log.info("【流程ID:"+rso.getRequestid()+"】删除数据处理...");
                    ObjectMapper objectMapper = new ObjectMapper();
                    String rsoString = null;
                    try {
                        rsoString = objectMapper.writeValueAsString(rso);
                    } catch (JsonProcessingException e) {
                        log.info(e.getMessage());
                    }
                    log.info(rsoString);
                    JSONObject rsojson = new JSONObject();
                    rsojson.put("cid", rso.getCid());
                    rsojson.put("username", rso.getUser().getLastname() + "(" + rso.getUser().getUID() + ")");
                    todolist.add(rsojson);
                }
                deljson.put("DelCount", deldatas.size());
                deljson.put("DelDatas", todolist);
            }

            //处理待办数据
            int todoCount = tododatas.size();
            if (todoCount > 0) {
                int count = 0;
                for (RequestStatusObj rso : tododatas) {//遍历当前发送的待办数据
                    count++;
                    log.info("待办数据处理："+count+"/"+todoCount);
                    SendJslytRequest obj = new SendJslytRequest();
                    log.info("【流程ID:"+rso.getRequestid()+"】待办消息接口调用...");
                    log.info(formatJson(todojson.toString()));
                    try {
                        todojson.put("taskId",rso.getCid()+"");
                        obj.sendTodoRequest(rso, todojson);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }

                }
            }



            //处理已办的待办数据
            int doneCount = donedatas.size();
            if (doneCount > 0) {
                int count = 0;
                for (RequestStatusObj rso : donedatas) {//遍历当前发送的待办数据
                    count++;
                    log.info("已办数据处理："+count+"/"+doneCount);
                    String passTaskId = (String)todojson.get("passTaskId");
                    String currentTaskId =  rso.getCid()+"";
                    log.info("currentTaskId:"+currentTaskId+",passTaskId:"+passTaskId);
                    if(!currentTaskId.equals(passTaskId)){
                        //已办消息处理
                        donejson.put("oprType", "submit"); // 已办
                        donejson.put("passActvName", rso.getNodename()); // 已办记录已办环节名称
                        donejson.put("passTaskId", currentTaskId);
                        donejson.put("passUserName", rso.getUser().getUsername());
                        donejson.put("passUid", rso.getUser().getUID());
                        if (rso.getIscomplete().equals("1")){
                            donejson.put("isEnd","true");
                        }else {
                            donejson.put("isEnd","false");
                        }

                        SendJslytRequest obj = new SendJslytRequest();
                        log.info("【流程ID:"+rso.getRequestid()+"】已办消息接口调用...");
                        log.info(formatJson(donejson.toString()));
                        try {
                            obj.sendTodoRequest(rso, donejson);
                        } catch (Exception e) {
                            log.error(e.getMessage());
                        }
                    }
                }
            }

            if (deldatas.size() > 0) {
                //处理推送的删除数据
                for (RequestStatusObj rso : deldatas) {//遍历当前发送的删除数据
                    SendJslytRequest obj = new SendJslytRequest();
                    log.info("【流程ID:"+rso.getRequestid()+"】删除消息接口调用...");
                    log.info(formatJson(deljson.toString()));
                    try {
                        obj.sendDelRequest(String.valueOf(rso.getRequestid()));
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                }

            }
        }
        log.info("Ecology统一待办数据推送金盛兰云台：end");
    }

    /**
     * 格式化JSON格式输出
     *
     * @param jsonStr
     * @return 返回指定格式化的数据
     */
    public String formatJson(String jsonStr) {
        if (null == jsonStr || "".equals(jsonStr))
            return "";
        StringBuilder sb = new StringBuilder();
        char last = '\0';
        char current = '\0';
        int indent = 0;
        boolean isInQuotationMarks = false;
        for (int i = 0; i < jsonStr.length(); i++) {
            last = current;
            current = jsonStr.charAt(i);
            switch (current) {
                case '"':
                    if (last != '\\') {
                        isInQuotationMarks = !isInQuotationMarks;
                    }
                    sb.append(current);
                    break;
                case '{':
                case '[':
                    sb.append(current);
                    if (!isInQuotationMarks) {
                        sb.append('\n');
                        indent++;
                        addIndentBlank(sb, indent);
                    }
                    break;
                case '}':
                case ']':

                    if (!isInQuotationMarks) {
                        sb.append('\n');
                        indent--;
                        addIndentBlank(sb, indent);
                    }
                    sb.append(current);
                    break;
                case ',':
                    sb.append(current);
                    break;
                default:
                    sb.append(current);
            }
        }

        return sb.toString();
    }

    /**
     * 添加space(缩进)
     *
     * @param sb
     * @param indent
     */
    private void addIndentBlank(StringBuilder sb, int indent) {
        for (int i = 0; i < indent; i++) {
            sb.append('\t');
        }
    }


    private static String getUsercodeByUid(int uid) {

        try {
            RecordSet recordSet = new RecordSet();
            String sql = "select textfield1 from hrmresource where id = '" + uid + "' ";

            recordSet.execute(sql);

            if (recordSet.next()) {
                // 从OA流程中提取参数
                String usercode = recordSet.getString("textfield1"); // 金盛兰云台用户编码
                // 记录返回结果
                //log.info("从手机号："+mobile+ " 获取的用户编码为："+usercode);
                if (StringUtils.isBlank(usercode)){
                    // 出错就按龙泽权的账号为已办人员
                    return "da7e1da96f5a459891dfd45ddee4f3a0";
                }
                return usercode;
            }
            // 出错就按龙泽权的账号为已办人员
            return "da7e1da96f5a459891dfd45ddee4f3a0";
        } catch (Exception e) {
            // 出错就按龙泽权的账号为已办人员
            return "da7e1da96f5a459891dfd45ddee4f3a0";
        }
    }


}